package com.sz.app.supplier.web.security;

import com.sz.biz.app.web.security.AbstractShiroConfiguration;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class SupplierShiroConfiguration extends AbstractShiroConfiguration {

    /**
     * Shiro的Web过滤器Factory 命名:shiroFilter<br />
     *
     * @param securityManager
     * @return
     */
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/api/v1/about", "anon");
        filterChainDefinitionMap.put("/api/v1/dict/**", "anon");

        filterChainDefinitionMap.put("/api/v1/auth/**", "anon");
        filterChainDefinitionMap.put("/api/v1/user/register/**","anon");
        filterChainDefinitionMap.put("/api/v1/sys/files/upload/**","anon");
        filterChainDefinitionMap.put("/api/v1/sys/files/download/**", "anon");
        filterChainDefinitionMap.put("/api/v1/**", "authc,kickout");
        filterChainDefinitionMap.put("/**", "anon");
        return createShiroFilterFactoryBean(securityManager, filterChainDefinitionMap);
    }

    /**
     * Shiro Realm
     */
    @Bean
    @Override
    public SupplierUserRealm createUserRealm() {
        SupplierUserRealm userRealm = new SupplierUserRealm();
        //告诉realm,使用credentialsMatcher加密算法类来验证密文
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        userRealm.setCachingEnabled(false);
        return userRealm;
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * 所以我们需要修改下doGetAuthenticationInfo中的代码;
     * ）
     * 可以扩展凭证匹配器，实现 输入密码错误次数后锁定等功能，下一次
     *
     * @return
     */
    @Override
    @Bean(name = "credentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        SupplierHashedCredentialsMatcher retryLimitHashedCredentialsMatcher =
                new SupplierHashedCredentialsMatcher(getCacheManager());

        retryLimitHashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
        retryLimitHashedCredentialsMatcher.setHashIterations(1);//散列的次数，比如散列两次，相当于 md5(md5(""));
        //storedCredentialsHexEncoded默认是true，此时用的是密码加密用的是Hex编码；false时用Base64编码
        retryLimitHashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);

        return retryLimitHashedCredentialsMatcher;
    }

    @Override
    protected String getActiveSessionsCacheName() {
        return "shiro-activeSessionCache-supplier";
    }
}

